document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value.trim();
        
        // 简单的表单验证
        if (!username) {
            showCenterModal('请输入用户名');
            return;
        }
        
        if (!password) {
            showCenterModal('请输入密码');
            return;
        }
        
        // 登录前清空localStorage，防止老数据影响
        localStorage.clear();
        
        // 发送登录请求到后端
        fetch('http://localhost:3000/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': sessionStorage.getItem('token') || ''
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        })
        .then(res => res.json())
        .then(data => {
            if (data.id) {
                // 登录成功，保存用户信息到sessionStorage和localStorage
                sessionStorage.setItem('userRole', data.role);
                sessionStorage.setItem('role', data.role); // 新增，保证前端能识别管理员
                sessionStorage.setItem('username', data.username);
                sessionStorage.setItem('userId', data.id);
                if (data.token) {
                  sessionStorage.setItem('token', data.token);
                }
                sessionStorage.setItem('isLoggedIn', 'true');
                
                // 同时保存到localStorage，确保建议提交时能获取到用户名
                localStorage.setItem('username', data.username);
                localStorage.setItem('userId', data.id);
                localStorage.setItem('role', data.role);
                
                showCenterModal('登录成功！', function() {
                  window.location.href = 'index.html';
                });
            } else {
                showCenterModal(data.error || '登录失败');
            }
        })
        .catch(err => {
            showCenterModal('登录请求失败');
            console.error(err);
        });
    });

    // 屏幕中心弹窗
    function showCenterModal(message, callback) {
        let modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.left = '0';
        modal.style.top = '0';
        modal.style.width = '100vw';
        modal.style.height = '100vh';
        modal.style.background = 'rgba(0,0,0,0.18)';
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '9999';
        modal.innerHTML = `<div style="background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:320px;text-align:center;">
            <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
            <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
            <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
        </div>`;
        document.body.appendChild(modal);
        document.getElementById('centerModalBtn').onclick = function() {
            document.body.removeChild(modal);
            if (callback) callback();
        };
    }

    // 游客登录按钮
    const guestLoginBtn = document.getElementById('guestLoginBtn');
    if (guestLoginBtn) {
        guestLoginBtn.addEventListener('click', function() {
            fetch('http://localhost:3000/api/guest-user', { method: 'POST' })
                .then(res => res.json())
                .then(data => {
                    if (data.guestCount && data.guestId) {
                        let msg = `欢迎，您是第${data.guestCount}位游客。`;
                        showCenterModal(msg, function() {
                            localStorage.clear();
                            sessionStorage.setItem('userRole', 'guest');
                            sessionStorage.setItem('userId', data.guestId);
                            sessionStorage.setItem('username', `游客${data.guestId}`);
                            sessionStorage.setItem('isLoggedIn', 'true');
                            
                            // 同时保存到localStorage
                            localStorage.setItem('username', `游客${data.guestId}`);
                            localStorage.setItem('userId', data.guestId);
                            localStorage.setItem('role', 'guest');
                            
                            window.location.href = 'index.html';
                        });
                    } else {
                        showCenterModal('游客登录失败');
                    }
                })
                .catch(() => showCenterModal('游客登录失败'));
        });
    }
}); 